package org.budo.time.impl;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import org.budo.time.Time;
import org.budo.time.TimeFormat;
import org.budo.time.TimePoint;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
 * 时间格式化规则 SimpleDateFormat 的线程安全的代理 yyyy-MM-dd yyyy-MM-dd HH:mm:ss.SSS
 * yyyyMMdd.HHmmss.SSS
 * 
 * @author lmw
 */
@ToString
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class BudoTimeFormat implements Serializable, TimeFormat {
    private static final long serialVersionUID = -6504816189392736328L;

    private String pattern;

    public TimePoint parse(String value) {
        if (null == value || value.trim().isEmpty()) {
            return new BudoTimePoint(null);
        }

        try {
            DateFormatFactory dateFormatFactory = DateFormatFactory.getCurrent();
            DateFormat dateFormat = dateFormatFactory.getDateFormat(this.getPattern());
            Date date = dateFormat.parse(value);
            return Time.when(date);
        } catch (ParseException e) {
            throw new RuntimeException("#45 parse error, value=" + value + ", pattern=" + this.getPattern() + ", this=" + this + ", e=" + e, e);
        }
    }

    public String format(Object date) {
        DateFormatFactory dateFormatFactory = DateFormatFactory.getCurrent();
        DateFormat dateFormat = dateFormatFactory.getDateFormat(this.getPattern());

        TimePoint timePoint = Time.when(date);
        return dateFormat.format(timePoint.toDate());
    }
}